const { exec } = require("child_process");
const { clearInterval } = require("timers");
const config = require('./config');

const execute = (command) => {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      if (error) {
        return reject(`Exec error: ${error.message}`);
      }
      if (stderr) {
          return reject(`Exec stderr: ${stderr}`);
      }
      console.log('job working');
      resolve(true);
    })
  })
}

let TIMER = null;

const restartServer = async () => {
  return await execute('systemctl restart apache2.service');
}

module.exports = async (request, response) => {
  const url = new URL(request.url, `http://${request.headers.host}`)
  const {pathname, searchParams: quertyString} = url;
  const apiKey = quertyString.get('key')

  if(!apiKey || apiKey != config.app.apiKey){
    return response.end('Please provide API key');
  }

  if(pathname == '/restart'){
    await restartServer();
    return response.end('Restarted server');
  }

  if(pathname == '/start'){
    TIMER = setInterval(async () => {
      try {
        await restartServer()
      } catch(err){
        console.error('Restart job failed: %s', err);
      }
    }, config.systemd.interval)
    return response.end('Started timer');
  }

  if(pathname == '/stop'){
    if(TIMER) clearInterval(TIMER), TIMER = null;
    return response.end('Stopped timer');
  }

  if(pathname == '/status'){
    const status = TIMER ? 'enabled' : 'disabled';
    return response.end(`Timer status: ${status}`);
  }
  
  response.end('path not found');

}